package common

import (
	"context"
	"fmt"
	"github.com/pkg/errors"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var Db *mongo.Client

func InitDB() (err error) {
	conf, err := GetConfig()
	if err != nil {
		return
	}
	uri := fmt.Sprintf("mongodb://rwuser:%v@%v:%v/%v?authSource=admin", conf.Password, conf.Host, conf.Port, conf.Dbname)
	// 设置客户端连接配置
	fmt.Println(uri)
	clientOptions := options.Client().ApplyURI(uri)
	var ctx = context.Background()
	// 连接到MongoDB
	Db, err = mongo.Connect(ctx, clientOptions)
	if err != nil {
		return errors.Wrap(err, "ERR: fail to connect")
	}
	// 检查连接
	err = Db.Ping(ctx, nil)
	if err != nil {
		return errors.Wrap(err, "ERR: fail to ping")
	}
	return nil
}

func GetDb() *mongo.Client {
	return Db
}

func init() {
	err := InitDB()
	if err != nil {
		log.Fatalf("add error info: %+v", err)
	}
}
